package first.endtoend

import org.springframework.dao.DataIntegrityViolationException

class FairPricesShopController
{

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def scaffold = true
    def springSecurityService

    def save()
    {
        def localityInstance = Locality.findById(params.localitySelect)
        Address adress
        if (localityInstance)
        {
            adress = new Address(nameStreet: params.nameStreet, numStreet: params.num, zipCode: params.zipCode, locality: localityInstance, localityName: localityInstance.name)
        } else
        {
            flash.message = message(code: 'default.not.found.locality.message')
            redirect(action: "create")
            return
        }
        if (adress != null)
        {
            adress.save()
            localityInstance.addresses.add(adress)
            localityInstance.save(flush: true)
        }

        def fairPricesShopInstance = new FairPricesShop(fpsName: params.fpsName, locality: localityInstance,).save(flush: true)
        println fairPricesShopInstance.toString()
        fairPricesShopInstance.addToAgents(Agent.findById(params.agents.id))
        fairPricesShopInstance.save(flush: true)


        if (!fairPricesShopInstance.save(flush: true))
        {

            render(view: "create", model: [fairPricesShopInstance: fairPricesShopInstance])
            return
        }


        flash.message = message(code: 'default.created.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), fairPricesShopInstance.id])
        redirect(action: "show", id: fairPricesShopInstance.id)
    }

    def index()
    {
        redirect(action: "list", params: params)
    }

    def list(Integer max)
    {

        params.max = Math.min(max ?: 10, 100)
        User userInstance = springSecurityService.currentUser
        Role roleAgent = Role.findByAuthority('ROLE_AGENT')

        Agent agentInstance
        if (userInstance.authorities.contains(roleAgent))
        {
            agentInstance = (Agent) userInstance
            getFpsByAgent(agentInstance)
        } else
        {
            [fairPricesShopInstanceList: FairPricesShop.list(params), fairPricesShopInstanceTotal: FairPricesShop.count()]
        }
    }

    def create()
    {
        [fairPricesShopInstance: new FairPricesShop(params)]
    }


    def show(Long id)
    {
        def fairPricesShopInstance = FairPricesShop.get(id)
        if (!fairPricesShopInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), id])
            redirect(action: "list")
            return
        }
        List<Family> familiesInFPS = Family.findAllByFps(fairPricesShopInstance)

        [fairPricesShopInstance: fairPricesShopInstance, families: familiesInFPS]
    }

    def edit(Long id)
    {
        def fairPricesShopInstance = FairPricesShop.get(id)
        if (!fairPricesShopInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), id])
            redirect(action: "list")
            return
        }
        def addressInstance = Address.findByLocalityName(fairPricesShopInstance.locality.name)

        [fairPricesShopInstance: fairPricesShopInstance, addressInstance: addressInstance, localityInstance: fairPricesShopInstance.locality]
    }

    def update(Long id, Long version)
    {
        def fairPricesShopInstance = FairPricesShop.get(id)
        def addressInstance = Address.findByLocality(fairPricesShopInstance.locality)
        if (!fairPricesShopInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), id])
            redirect(action: "list")
            return
        }

        if (version != null)
        {
            if (fairPricesShopInstance.version > version)
            {
                fairPricesShopInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'fairPricesShop.label', default: 'FairPricesShop')] as Object[],
                        "Another user has updated this FairPricesShop while you were editing")
                render(view: "edit", model: [fairPricesShopInstance: fairPricesShopInstance])
                return
            }
        }

        println("####PARAS = " + params)

        fairPricesShopInstance.properties = params
        addressInstance.properties = params

        fairPricesShopInstance.locality = Locality.findById(Long.valueOf(params.localitySelect))

        addressInstance.save(flush: true)


        for (agentId in params.agents.id)
        {
            fairPricesShopInstance.addToAgents(Agent.findById(Long.valueOf(agentId)))
        }


        if (!fairPricesShopInstance.save(flush: true))
        {
            render(view: "edit", model: [fairPricesShopInstance: fairPricesShopInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), fairPricesShopInstance.id])
        redirect(action: "show", id: fairPricesShopInstance.id)
    }

    def delete(Long id)
    {
        def fairPricesShopInstance = FairPricesShop.get(id)
        if (!fairPricesShopInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), id])
            redirect(action: "list")
            return
        }

        try
        {
            fairPricesShopInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e)
        {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'fairPricesShop.label', default: 'FairPricesShop'), id])
            redirect(action: "show", id: id)
        }
    }

    def getFpsByAgent(Agent anAgent)
    {
        if (anAgent.fps)
        {
            [fairPricesShopInstanceList: anAgent.fps, fairPricesShopInstanceTotal: 1]

        } else
        {
            //nothing to render
            [fairPricesShopInstanceList: anAgent.fps, fairPricesShopInstanceTotal: 0]

        }
    }
}
